package com.sinocare.common.result;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;
@Data
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Result<T> implements Serializable {
    private static final long serialVersionUID = -5799884309668185705L;
    //是否成功
    private Boolean success;
    //返回状态码
    private Integer code;
    //返回信息
    private String message;
    //LayUI统计记录数
    private Long count;
    //返回数据
    private T data;
    public Result(){}

    //创建ResultBean对象，接收数据
    protected static <T> Result<T> build(T data) {
        //实例化Result对象
        Result<T> result = new Result<T>();
        if (data != null)
            result.setData(data);
        return result;
    }



    public static <T> Result<T> build(T body, ResultCode resultCode) {
        Result<T> result = build(body);
        result.setCode(resultCode.getCode());
        result.setMessage(resultCode.getMessage());
        return result;
    }

    public static <T> Result<T> build(Integer code, String message) {
        Result<T> result = build(null);
        result.setCode(code);
        result.setMessage(message);
        return result;
    }

    public static<T> Result<T> ok(){
        return Result.ok();
    }



    /**
     * 操作成功
     * @param data
     * @param <T>
     * @return
     */
    public static<T> Result<T> ok(ResultCode resultCode, T data){
        Result<T> result = build(data); //调用build方法
        result.setSuccess(true);
        //操作成功，默认为true
        //SUCCESS(200, "成功"),
        result.setCode(resultCode.getCode());  //200
        result.setMessage(resultCode.getMessage()); //"成功"
        return result;
    }



    public static<T> Result<T> ok(ResultCode resultCode, Long count, T data){
        Result<T> result = ok(resultCode, data);
        result.setCount(count);
        return result;
    }

    public static<T> Result<T> fail(){
        return Result.fail();
    }

    /**
     * 操作失败
     * @param data
     * @param <T>
     * @return
     */
    public static<T> Result<T> fail(ResultCode resultCode, T data){
        Result<T> result = build(data);
        return build(data, ResultCode.FAIL);
    }

    public Result<T> message(String msg){
        this.setMessage(msg);
        return this;
    }

    public Result<T> code(Integer code){
        this.setCode(code);
        return this;
    }

    public boolean isOk() {
        if(this.getCode().intValue() == ResultCode.SUCCESS.getCode().intValue()) {
            return true;
        }
        return false;
    }
}
